package face.pay.api.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import face.pay.api.order.service.IOrderService;
import face.pay.constant.ChannelCode;
import face.pay.constant.OrderStatus;
import face.pay.constant.OrderType;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.MathUtil;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private TerminalInfoDao terminalInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Transactional(rollbackFor = Exception.class)
    public ResultMessage unify_order(String orderInfo,String ip){

        log.info("设备下单:"+orderInfo);
        log.info("设备网络IP:"+ip);

        JSONObject jsonObject = JSON.parseObject(orderInfo);

        OrderInfo order  = jsonObject.parseObject(orderInfo,OrderInfo.class);

        order.setIp(ip);
        String deviceId  = order.getDevice_id();

        String imei =   jsonObject.getString("imei");

        String sn =   jsonObject.getString("sn");

        if(StringUtils.isNotBlank(deviceId) && order.getTotalFee()!=null && new Long(0).compareTo(order.getTotalFee())==-1 ){
            deviceId = deviceId.toUpperCase();
            TerminalInfo terminalInfo = this.terminalInfoDao.getByDeviceId(deviceId);

            /**
             * 暂时去掉imei验证
             */
            if (terminalInfo != null && terminalInfo.getStoreId()!=null) {
                //暂时取消验证
                //&& imei.equals(terminalInfo.getImei()
                if(StringUtils.isNotBlank(imei)) {

                    log.info("设备信息:" + terminalInfo);

                    if (StringUtils.isNotBlank(sn)) {
                        log.info("更新设备SN:" + sn);
                        terminalInfo.setSn(sn);

                    }
                    terminalInfo.setImei(imei);
                    log.info("更新设备imei:" + imei);
                    this.terminalInfoDao.update(terminalInfo);

                    if (StringUtils.isBlank(sn)) {
                       sn = terminalInfo.getSn();
                    }

                    Integer storeId = terminalInfo.getStoreId();
                    Integer oemId   = terminalInfo.getOemId();
                    Integer userId  = terminalInfo.getUserId();

                    StoreInfo storeInfo = this.storeInfoDao.getById(storeId);

                    if (storeInfo != null) {

                        Long total_fee = order.getTotalFee();
                        log.info("门店信息:" + storeInfo.toString());

                        OemInfo oemInfo = this.oemInfoDao.getOemInfoById(oemId);

                        Integer enterpriseId = storeInfo.getEnterpriseId();

                        EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.getById(enterpriseId);
                        /**
                         * 获取OEM 微信服务商信息
                         */
                        String appId = oemInfo.getAppId();
                        String apiKey = oemInfo.getApiKey();
                        String mchId = oemInfo.getMchId();

                        String subMchId = enterpriseInfo.getWxSubMchId();
                        Double subsidyRate = enterpriseInfo.getWxSubsidyRate() == null ? new Double(0) : enterpriseInfo.getWxSubsidyRate();
                        Long   subsidyMoney = MathUtil.profit(total_fee, subsidyRate);

                        order.setStoreId(storeId);
                        order.setOemId(oemId);
                        order.setUserId(userId);
                        order.setSubsidyMoney(subsidyMoney);
                        order.setTerminalId(terminalInfo.getId());
                        order.setSn(sn);
                        order.setStatus(0);

                        Integer scene = order.getScene();
                        /**
                         * 默认是0 真实设备下单
                         */
                        if(scene==null){
                            order.setScene(0);
                        }

                        this.orderInfoDao.insert(order);

                        Map resultMap = new HashMap();
                        String out_trade_no = String.valueOf(order.getId());
                        resultMap.put("out_trade_no", out_trade_no);
                        resultMap.put("store_id",  storeId);
                        resultMap.put("device_id", deviceId);
                        resultMap.put("total_fee", order.getTotalFee());

                        resultMap.put("appid",  appId);
                        resultMap.put("mch_id", mchId);
                        resultMap.put("sub_mch_id", subMchId);

                        log.info("下单成功:"+resultMap);
                        return ResultMessage.createSuccess("下单成功", resultMap);

                    }else{
                        log.info("未绑定门店，下单失败");
                        return ResultMessage.createFail("未绑定门店，下单失败");

                    }

                }else {
                    log.info("设备信息发生变化，下单失败");
                    return ResultMessage.createFail("设备信息发生变化，下单失败");
                }

            }

        }else {
            log.info("下单失败");
          return   ResultMessage.createFail("下单失败，参数错误");
        }

        return  ResultMessage.createFail("下单失败");
    };

    @Override
    public ResultMessage checkStatus(String dataJson) {

        log.info("扫码支付订订单结果查询"+dataJson);

        Map<String,Object> map = JSON.parseObject(dataJson);

        String out_trade_no = map.get("out_trade_no")==null?"0":map.get("out_trade_no").toString();

        Long orderId  = Long.valueOf(out_trade_no);

        OrderInfo orderInfo = this.orderInfoDao.getById(orderId);

        String status = OrderStatus.NOTPAY;

        Map<String,String> resultMap =  new HashMap<>();


        if(orderInfo!=null){

            Integer order_status =  orderInfo.getStatus();

            status =  OrderStatus.getStatus(order_status);

            resultMap.put("out_trade_no",out_trade_no);
            resultMap.put("type",orderInfo.getType());
            resultMap.put("payType",orderInfo.getPayType());
            resultMap.put("total_fee",String.valueOf(orderInfo.getTotalFee()));
            resultMap.put("act_fee",String.valueOf(orderInfo.getActFee()));

            resultMap.put("status",status);
            Long totalFee = orderInfo.getTotalFee();

            String message  = orderInfo.getMessage();

            if(ChannelCode.WECHAT.equals(orderInfo.getChannelCode())){
                if(OrderStatus.SUCCESS.equals(status)){
                    message +=MathUtil.transForMoney(totalFee)+"元";

                }
            }
            resultMap.put("status_desc",message);

            ResultMessage resultMessage =   ResultMessage.createSuccess(resultMap);

            String  result = JSON.toJSONString(resultMessage);

            log.info(result);

            return  resultMessage;


        }else {
            return  ResultMessage.createFail("订单不存在");
        }
    }
}
